<template>
  <div class="xtx-goods-page">
    <div v-if="loading"
      class="container">
      <div class="loading"></div>
    </div>
    <div v-else
      class="container">
      <XtxBread>
        <XtxBreadItem to="/">首页</XtxBreadItem>
        <XtxBreadItem :to="`/category/${goods.categories[1].id}`">
          {{ goods.categories[1].name }}
        </XtxBreadItem>
        <XtxBreadItem>{{ goods.name }}</XtxBreadItem>
      </XtxBread>
      <!-- 商品信息 -->
      <div class="goods-wrapper">
        <div class="media">
          <XtxImageView :images="goods.mainPictures"></XtxImageView>
          +
          <GoodsSales />
        </div>
        <div class="spec">
          +
          <GoodsInfo :goods="goods" />
          <!-- sku组件 -->
          <XtxSku :goods="goods"
            @change="changeSku"></XtxSku>
          <!-- 数量 -->
          <XtxNumbox :min="1"
            v-model="count"
            label="数量" />
          <!-- 按钮 -->
          <XtxButton type="primary"
            style="margin-top: 20px; margin-left: 60px">
            加入购物车
          </XtxButton>
        </div>
      </div>
      +
      <!-- 商品底部 -->
      +
      <GoodsFooter :goods="goods" />
    </div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
import GoodsSales from "./components/goods-sales.vue";
import GoodsInfo from "./components/goods-info.vue";
import { getGoods } from "@/api/goods";
import { onBeforeRouteUpdate, useRoute } from "vue-router";
import GoodsFooter from "./components/goods-footer.vue";
export default {
  name: "xtx-goods-page",
  components: { GoodsSales, GoodsInfo, GoodsFooter },
  setup () {
    const route = useRoute();
    const goods = ref({});
    const loading = ref(true)
    // 加载数据函数
    const loadData = async (id) => {
      loading.value = true
      const data = await getGoods(id);
      goods.value = data.result;
      loading.value = false
    };
    // 初始化加载
    onMounted(() => loadData(route.params.id));
    // 将来切换商品加载
    onBeforeRouteUpdate((to, from, next) => {
      loadData(to.params.id);
      next();
    });
    // 选择SKU
    const changeSku = (sku) => {
      console.log(sku);
    };
    // 数量
    const count = ref(1);
    return { goods, changeSku, count, loading };
  },
};
</script>

<style lang="less" scoped>
.loading {
  height: 600px;
  border-top: 72px solid #f5f5f5;
  background: #fff url(../../assets/images/load.gif) no-repeat center / 80px 80px;
}
.goods-wrapper {
  display: flex;
  background: #fff;
  padding: 40px;
  .media {
    width: 480px;
    margin-right: 40px;
  }
}
</style>  